package wonder.settings;

import java.io.File;
import java.io.InputStream;
import java.util.Map;

import org.slf4j.Logger;

import wonder.SWServiceFactory;
import wonder.tools.JsonHelper;
import wonder.tools.LoggerHelper;
import wonder.tools.StreamHelper;

public class SettingsManager {
    private static final Logger logger = LoggerHelper.getLogger();
    private static final String USER_HOME_PROPERTY = "user.home";
    private static final String PACKAGED_CONF = "/default-configuration.json";
    private static final String DEPLOYED_7W_KEY = "wonders";

    private static final String DEPLOYED_CONF = ".7w-configuration.json";
    private static final String DEPLOYED_7W = ".7w-wonders.json";

    public static void standalone() throws Exception {
        InputStream isc = SettingsManager.class
                .getResourceAsStream(PACKAGED_CONF);
        SWServiceFactory.getInstance().configure(isc);
    }

    public static void deploy() throws Exception {
        String userDir = System.getProperty(USER_HOME_PROPERTY);
        logger.debug("{}", userDir);

        InputStream isc = SettingsManager.class
                .getResourceAsStream(PACKAGED_CONF);
        Map<String,Object> settings = JsonHelper.loadJson(isc);

        InputStream isw = SettingsManager.class
                .getResourceAsStream((String)settings.get(DEPLOYED_7W_KEY));
        File deployed7w = new File(userDir, DEPLOYED_7W);
        StreamHelper.inputStreamToFile(isw, deployed7w);

        settings.put(DEPLOYED_7W_KEY, deployed7w.getAbsolutePath());
        File deployedConf = new File(userDir, DEPLOYED_CONF);
        JsonHelper.saveJson(deployedConf, settings);

        load();
    }

    public static void undeploy() {
        String userDir = System.getProperty(USER_HOME_PROPERTY);

        new File(userDir, DEPLOYED_CONF).delete();
        new File(userDir, DEPLOYED_7W).delete();
    }

    public static void load() throws Exception {
        String userDir = System.getProperty(USER_HOME_PROPERTY);
        File deployedConf = new File(userDir, DEPLOYED_CONF);
        SWServiceFactory.getInstance()
                .configure(deployedConf.getAbsolutePath());
    }

    public static void save() {
        // TODO save settings
    }
}
